<?php
class Packing_listController extends Controller {
    const PAGE_SIZE=10;
	
    const CONTROLLER_ID = 1;
    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
        	'accessControl', // perform access control for CRUD operations
        	'AjaxOnly + showwarehousecargo',
        );
    }
	
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
        	array('allow',  // allow all users to perform 'index' and 'view' actions
        		'actions'=>array(''),
        		'users'=>array('*'),
        	),
        	array('allow', // allow authenticated user to perform 'create' and 'update' actions
        		'actions'=>array('create','update','report','list','delete','makereport','showwarehousecargo','view','removecargo','newcreate','addcargo'),
        		'users'=>array('@'),
        	),
        	array('allow', // allow admin user to perform 'admin' and 'delete' actions
        		'actions'=>array('admin'),
        		'users'=>array('admin'),
        	),
        	array('deny',  // deny all users
        		'users'=>array('*'),
        	),
        );
    }

    /**
     * Displays a particular model.
     */
    public function actionMakeReport(){
        $model = $this->loadModel();
        $cargo = $model->cargos;//Yii::app()->db->createCommand('SELECT * FROM cargo limit 0,20')->queryAll();
        $package = $model->packages;
        $rawData = array();
        foreach($package as $item) {
            $_data['marking'] = $item->marking;
            $_data['qty'] = $item->detail->qty;
            $_data['wt'] = $item->detail->wt;
            $_data['m3'] = $item->detail->m3;
            if(!empty($item->detail->length) && !empty($item->detail->width) && !empty($item->detail->height)) {
                $_data['dimension'] = $item->detail->length.' X '.$item->detail->width.' X '.$item->detail->height;
                $_data['m3'] = '('.$_data['m3'].')';
            }
            else
                $_data['dimension'] = '-';
            $rawData[] = $_data;
        }
        foreach($cargo as $item) {
            $_data['marking'] = $item->marking;
            $_data['qty'] = $item->dimension->qty;
            $_data['wt'] = $item->dimension->wt;
            $_data['m3'] = $item->dimension->m3;
            if(!empty($item->dimension->length) && !empty($item->dimension->width) && !empty($item->dimension->height)) {
                $_data['dimension'] = $item->dimension->length.' X '.$item->dimension->width.' X '.$item->dimension->height;
                $_data['m3'] = '('.$_data['m3'].')';
            }
            else
                $_data['dimension'] = '-';
            $rawData[] = $_data;
        }
        $pdf = new makePdf;
        $pdf->setSize('A4', 'P');
        
        $pagination = new CPagination(count($rawData));
        $pagination->setPageSize(10);
        for($i=0;$i<=$pagination->getPageCount()-1;$i++){
            $pdf->renderPartial('packing_list', array('model'=>$model,'data'=>  array_slice($rawData, $i*10, 10),'pagination'=>$pagination));
        }
        $pdf->stream('packing list');
    }
    public function actionAddCargo(){
        $model = new packing_list;
        if(Yii::app()->request->isPostRequest) {
            $model = $this->loadModel();
            $cargo = $this->getModel(cargo::model(),'cargo_id');
            $cargo->setScenario('packing_list');
            $cargo->status = "Packing";
            if(!$model->Add($cargo,'packing_id')) {
                    if(Yii::app()->request->isAjaxRequest) {
                            echo CJSON::encode(array('formerror'=>'Error'));
                            Yii::app()->end();
                    }
                    Yii::app()->user->setFlash('Saving Error');
            }
            if(Yii::app()->request->isAjaxRequest) {
                    echo CJSON::encode(array('id'=>$model->id));
                    Yii::app()->end();
            }
        }
    	if(Yii::app()->request->isAjaxRequest){
            echo $this->renderPartial('_list',array('model'=>$model),true,true);
            Yii::app()->end();
        }
        $this->render('_list',array(
                'model'=>$model,
        ));
    }
    public function actionRemoveCargo(){
    	$model = cargo::model()->find('id=:id AND packing_id=:packing_id',array(':id'=>$_GET['cargo_id'],':packing_id'=>$_GET['id']));
    	if($model === null) {
    		if(Yii::app()->request->isAjaxRequest) {
    			echo CJSON::encode(array('formerror'=>'Error'));
    			Yii::app()->end();
    		}
    		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    	}
    	else {
    		$model->packing_id = 0;
    		$model->status = "Warehouse";
    		if(!$model->save()){
    			if(Yii::app()->request->isAjaxRequest) {
    				echo CJSON::encode(array('formerror'=>'Remove error'));
    				Yii::app()->end();
    			}
    			Yii::app()->user->setFlash('Removing error');
    		}
    	}    	
    	if(Yii::app()->request->isAjaxRequest) {
    		Yii::app()->end();
    	}
    	$this->redirect(Yii::app()->user->getReturnUrl());
    }
    public function actionView() {
    	$model = $this->loadModel();
    	$package = new packing_list_packages;
    	$package->packing_list_id = $model->id;
    	$cargo = new cargo;
    	$cargo->packing_id = $model->id;
    	if(isset($_GET['searchText']))
    		$cargo->searchText = $_GET['searchText'];
    	$this->render('view',array(
            'model'=>$model,
    		'cargo'=>$cargo,
    		'package'=>$package,
        ));
    }
    public function actionShowWarehouseCargo(){
            $model = new cargo;
            if(isset($_GET['searchText']))
                    $model->searchText = $_GET['searchText'];
            echo $this->renderPartial('WarehouseCargoGrid',array('model'=>$model,'packing_id'=>$_GET['packing_id']),true,true);
    }
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionReport() {
    	$packing_list = $this->loadModel();
    	//$this->render('report/packing_list');
    	if(Yii::app()->request->isAjaxRequest)
    		echo $this->renderPartial('_report', array('packing_list'=>$packing_list), true, true);
    	else
    		$this->render('_viewreport',array('model'=>$packing_list));
    }
    public function actionCreate(){
    	$model['packing'] = new packing_list;
    	$model['package'][0] = new packing_list_packages;
    	$model['package_dimension'][0] = new packing_list_packages_dimension;
    	$company = new company;
    	if(isset($_GET['searchText']))
			$company->cname = $_GET['searchText'];
    	if(isset($_POST['packing_list'])) {
    		$model['packing']->attributes = $_POST['packing_list'];
    		$this->AssignData($model['package'],'packing_list_packages');
    		$this->AssignData($model['package_dimension'],'packing_list_packages_dimension');
    		$this->validateModels($model);
    		$ajax = (isset($_POST['ajax']) && $_POST['ajax']==='packing-list-form' && Yii::app()->request->isAjaxRequest)?true:false;
            $transaction = Yii::app()->db->beginTransaction();
            try {
    			if(!$model['packing']->save())
    				throw new Exception('Save error');
    			$model['packing']->generateRef('ref');
    			$transaction->commit();
    			if($ajax){
					echo CJavaScript::jsonEncode(array('id'=>$model['packing']->id));
					Yii::app()->end();
				}
				else
					$this->redirect(array('view','id'=>$model['packing']->id));
            }
            catch(Exception $e) {
            	$transaction->rollback();
            	if($ajax){
            		echo CJavaScript::jsonEncode(array('formerror'=>$e->getMessage()));
            		Yii::app()->end();
            	}
            }
    	}
    	if(Yii::app()->request->isAjaxRequest){
			echo $this->renderPartial('create',array('model'=>$model,'company'=>$company),true,true);
			Yii::app()->end();	
		}			
		$this->render('create',array(
			'model'=>$model,
			'company'=>$company
		));
    }
    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate() {
        $model['packing'] = $this->loadModel();
        if (isset($_POST['packing_list'])) {
            $model['packing']->attributes = $_POST['packing_list'];
            $this->validateModels($model);
            $ajax = (isset($_POST['ajax']) && $_POST['ajax'] === 'packing-list-form' && Yii::app()->request->isAjaxRequest) ? true : false;
            $transaction = Yii::app()->db->beginTransaction();
            try {
                if (!$model['packing']->save())
                    throw new Exception('Save error');
                $transaction->commit();
                if ($ajax) {
                    echo CJavaScript::jsonEncode(array('id' => $model['packing']->id));
                    Yii::app()->end();
                }
                else
                    $this->redirect(array('view', 'id' => $model['packing']->id));
            } catch (Exception $e) {
                $transaction->rollback();
                if ($ajax) {
                    echo CJavaScript::jsonEncode(array('formerror' => $e->getMessage()));
                    Yii::app()->end();
                }
            }
        }
        if (Yii::app()->request->isAjaxRequest) {
            echo $this->renderPartial('update', array('model' => $model), true, true);
            Yii::app()->end();
        }
        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete() {
        if(Yii::app()->request->isPostRequest) {
        // we only allow deletion via POST request
            $model = $this->loadModel();
            foreach($model->cargos as $cargo) {

            }

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_POST['ajax']))
                $this->redirect(array('index'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * s all models.
     */
    public function actionList(){
	$model = new packing_list;
        $this->render('list',array(
            'model'=>$model,
        ));
    }
    public function actionIndex() {
        $dataProvider=new CActiveDataProvider('packing_list', array(
            'pagination'=>array(
            'pageSize'=>self::PAGE_SIZE,
            ),
        ));
		$model = new packing_list;
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        	'model'=>$model,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $dataProvider=new CActiveDataProvider('packing_', array(
            'pagination'=>array(
            'pageSize'=>self::PAGE_SIZE,
            ),
        ));

        $this->render('admin',array(
            'dataProvider'=>$dataProvider,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel() {
        if($this->_model===null) {
            if(isset($_GET['id']))
                $this->_model=packing_list::model()->findbyPk($_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }
}
